import { Breadcrumb, Button, Table, Space, Modal, TableProps, message, Flex } from 'antd';
import React, { FC } from 'react';
import { FormPanel, Utils, type FormPanelObject, InputType } from 'lfun-bg-comp';
import { useNavigate } from 'react-router-dom';
import _ from 'lodash';
import dayjs from 'dayjs';
import { PageContainer } from '@/component/page-container';
import { GENDER } from '@/constant/basicOptions';
import { PAGINATIONCONFIG } from '@/constant/page';
import { DIS_STUDENT_APPROVALATATUS, ID_TYPE, STUDENT_APPROVALATATUS } from '@/constant/studentOptions';
import { listGrades } from '@/service/unit/grades';
import utils, { getPathRoot } from '@/utils';
import { listClasses } from '@/service/unit/classes';
import { StuNewStudentSrv } from '@/service/student';
import { TNewStudents } from '@/service/student/types';
import SearchInput from '@/view/component/searchInput';
import { searchPlanningSchoolByName } from '@/service/unit/planning';
import PermissionButton, { isPermissionOperate } from '@/component/permission-button';

const Groups: FC = () => {
  const [curForm, setCurForm] = React.useState<any>();
  const [value, setValue] = React.useState([]);
  const [total, setTotal] = React.useState(0);
  const [pageSize, setPageSize] = React.useState(10);
  const [pageIndex, setPageIndex] = React.useState(1);
  const navigate = useNavigate();
  const [selectItems, setSelectItems] = React.useState([]);
  const [visible, setVisible] = React.useState(false);
  const [isMore, setIsMore] = React.useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = React.useState<React.Key[]>([]);
  const [searchValue] = React.useState({ status: 'enrollment' });
  const [looading, setLoading] = React.useState(false);

  const init = async (pageIndex, pageSize) => {
    setLoading(true);
    utils.showLoading();
    const pamas: TNewStudents.TReqNewStudentsDisParams = {
      ...(curForm?.getFieldsValue() || searchValue),
      page: pageIndex,
      per_page: pageSize,
    };
    const res = await StuNewStudentSrv.distributelist(pamas);
    if (res.success) {
      if (res?.data?.items.length === 0) {
        setValue([]);
      } else {
        setValue(
          res?.data?.items?.map(item => {
            return {
              ...item,
              key: item.student_id,
            };
          })
        );
      }
      setTotal(res?.data?.total);
      setPageIndex(pageIndex);
      setPageSize(pageSize);
    }
    utils.hideLoaing(res.success);
    setLoading(false);
  };
  React.useEffect(() => {
    init(1, pageSize);
  }, []);

  const pageChange = (pageIndex, pageSize) => {
    init(pageIndex, pageSize);
    setSelectedRowKeys([]);
    setSelectItems([]);
  };

  const handleView = record => {
    navigate(`${getPathRoot()}/newstudent/details/${record.id}`, { state: record });
  };
  const columns: TableProps['columns'] = [
    {
      title: '姓名',
      dataIndex: 'student_name',
      key: 'student_name',
      width: 100,
      fixed: 'left',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render(v, record, index) {
        return _.find(DIS_STUDENT_APPROVALATATUS, { value: v })?.label;
      },
    },
    {
      title: '班级',
      dataIndex: 'class_id',
      key: 'class_id',
      width: 100,
      render(v, record, index) {
        return v || '-';
      },
    },
    {
      title: '分班时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 150,
      render: v => {
        if (v) {
          return dayjs(v).format('YYYY-MM-DD');
        }
        return '';
      },
    },
    {
      title: '身份证件类型',
      dataIndex: 'id_type',
      key: 'id_type',
      width: 200,
      render: v => {
        return _.find(ID_TYPE, { value: v })?.label;
      },
    },
    {
      title: '身份证件号',
      dataIndex: 'id_number',
      key: 'id_number',
      width: 200,
    },
    {
      title: '报名号',
      dataIndex: 'enrollment_number',
      key: 'enrollment_number',
      width: 100,
    },
    {
      title: '性别',
      dataIndex: 'student_gender',
      key: 'student_gender',
      width: 100,
      render(v, record, index) {
        return _.find(GENDER, { value: v })?.label;
      },
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      //width: 200,
      fixed: 'right',
      align: 'center',
      hidden: !isPermissionOperate(),
      render: (text, record) => (
        <Space>
          <PermissionButton permission="view">
            <Button type="link" onClick={() => handleView(record)}>
              查看
            </Button>
          </PermissionButton>
          <PermissionButton permission="banding">
            <Button
              type="link"
              onClick={() => {
                setSelectItems([record]);
                handleClassroom('one', record);
              }}
            >
              分班
            </Button>
          </PermissionButton>
        </Space>
      ),
    },
  ];

  const list = [
    {
      title: '',
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      inputs: [
        {
          label: '报名号',
          name: 'enrollment_number',
          key: 'enrollment_number',
        },
        {
          label: '学校',
          name: 'school_id',
          key: 'school_id',
          inputType: InputType.children,
          children: (
            <SearchInput
              onLoadOption={null}
              searchFunction={async v => {
                const res = await searchPlanningSchoolByName(v);
                if (res.success) {
                  return res.data.map(item => ({
                    label: item.planning_school_name,
                    value: item.id,
                  }));
                }
                return [];
              }}
              randerOption={option => option}
            />
          ),
        },
        {
          label: '身份证件类型',
          name: 'id_type',
          key: 'id_type',
          inputType: InputType.select,
          renderOption: ID_TYPE,
        },
        {
          label: '姓名',
          name: 'student_name',
          key: 'student_name',
          textRange: [0, 20],
        },
        {
          label: '分班时间',
          name: 'created_at',
          key: 'created_at',
          inputType: InputType.date,
        },
        {
          label: '性别',
          name: 'student_gender',
          key: 'student_gender',
          inputType: InputType.select,
          renderOption: GENDER,
        },
        {
          label: '班级',
          name: 'class_id',
          key: 'class_id',
          inputType: InputType.select,
          renderOption: async () => {
            const res = await listClasses(Utils.getProps('schoolInfo')?.school_id);
            if (res.success) {
              const list = res?.data?.items?.map(item => {
                return {
                  label: `${item.class_name}班`,
                  value: item.id,
                };
              });
              return list;
            }
            return [];
          },
        },
        {
          label: '状态',
          name: 'status',
          key: 'status',
          inputType: InputType.select,
          renderOption: STUDENT_APPROVALATATUS.slice(0, 2),
        },
      ],
    },
  ];
  const buildBtns = () => {
    return [
      // <Button type="primary">摇号分班</Button>,
      <PermissionButton permission="export">
        <Button type="primary">导出</Button>
      </PermissionButton>,
    ];
  };

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const handleClassroom = (type, data = {}) => {
    if (type === 'more') {
      setIsMore(true);
      setVisible(true);
    } else {
      setIsMore(false);
      setVisible(true);
    }
  };

  return (
    <PageContainer header={<Breadcrumb items={[{ title: '分班管理' }]} />}>
      <FormPanel
        btnsAlign="right"
        restBtnText="重置"
        submitBtnText="查询"
        buttons={buildBtns()}
        values={searchValue}
        onLoad={form => {
          setCurForm(form);
        }}
        onFinish={() => {
          init(1, pageSize);
        }}
        template={list}
      />
      <Flex gap="small" wrap="wrap" style={{ marginBottom: 20 }}>
        <PermissionButton permission="batch_banding">
          <Button
            type="primary"
            onClick={() => {
              if (selectedRowKeys.length === 0) {
                message.info('请选择学生');
                return;
              }
              const curItems: any = value.filter(item => {
                return selectedRowKeys?.includes(item.key);
              });
              setSelectItems([...curItems]);
              handleClassroom('more');
            }}
          >
            批量分班
          </Button>
        </PermissionButton>
      </Flex>
      <Table
        dataSource={value}
        columns={columns}
        rowSelection={rowSelection}
        loading={looading}
        scroll={{ x: 'max-content' }}
        pagination={{ ...PAGINATIONCONFIG, total, pageSize, current: pageIndex, onChange: pageChange }}
      />
      <ClassroomModal
        visible={visible}
        isMore={isMore}
        onCancel={() => setVisible(false)}
        onSave={async values => {
          const res: any = await StuNewStudentSrv.distribute(
            values.class,
            selectItems.map(item => item.student_id)
          );
          if (res.success) {
            setVisible(false);
            setSelectedRowKeys([]);
            setSelectItems([]);
            init(1, pageSize);
            return message.success('分配成功');
          }
          message.error('分配失败');
        }}
        values={selectItems}
      />
    </PageContainer>
  );
};

export default Groups;

type TClassroomModel = {
  visible: boolean;
  onCancel: () => void;
  onSave: Function;
  isMore: boolean;
  values: any[];
  // formData?: any;
};

const ClassroomModal: React.FC<TClassroomModel> = ({ visible, onCancel, onSave, isMore, values }) => {
  const [curForm, setCurForm] = React.useState(null);
  const list = [
    {
      title: '',
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      span: 12,
      inputs: [
        {
          label: '选择年级',
          name: 'grade',
          key: 'grade',
          required: true,
          inputType: InputType.select,
          relationFields: ['class'],
          renderOption: async () => {
            const res = await listGrades(Utils.getProps('schoolInfo')?.school_id);
            if (res.success) {
              return res?.data?.items?.map(item => {
                return {
                  label: item.grade_name,
                  value: item.id,
                };
              });
            }
            return [];
          },
        },
        {
          label: '选择班级',
          name: 'class',
          key: 'class',
          required: true,
          inputType: InputType.select,
          renderOption: async (form: FormPanelObject) => {
            if (!form.getFieldValue('grade')) {
              return [];
            }
            const res = await listClasses(Utils.getProps('schoolInfo')?.school_id, form.getFieldValue('grade'));
            if (res.success) {
              const list = res?.data?.items?.map(item => {
                return {
                  label: `${item.class_name}`,
                  value: item.id,
                };
              });
              return list;
            }
            return [];
          },
        },
      ],
    },
  ];

  const columns: TableProps['columns'] = [
    {
      title: '姓名',
      dataIndex: 'student_name',
      key: 'student_name',
    },
    {
      title: '身份证件类型',
      dataIndex: 'id_type',
      key: 'id_type',
      render: (text: string) => {
        return _.find(ID_TYPE, { value: text })?.label;
      },
    },
    {
      title: '身份证件号',
      dataIndex: 'id_number',
      key: 'id_number',
    },
    {
      title: '报名号',
      dataIndex: 'enrollment_number',
      key: 'enrollment_number',
    },
  ];

  const handleSave = () => {
    curForm
      .validateFields()
      .then(newVals => {
        onSave(newVals);
      })
      .catch(err => {
        console.log(err);
      });
  };

  return (
    <Modal
      title={isMore ? '批量分班' : '分班'}
      width="60%"
      open={visible}
      onOk={handleSave}
      onCancel={onCancel}
      okText="确定分班"
    >
      <FormPanel
        buttonsDisplay={null}
        onLoad={(formPanelObject: FormPanelObject) => {
          setCurForm(formPanelObject);
        }}
        template={list}
      />
      <Table columns={columns} scroll={{ x: 'max-content' }} dataSource={values} bordered pagination={false} />
    </Modal>
  );
};
